package src.lib;

public class Exec {
	String splitString, _long, _short;

	public Exec() {
		this.splitString = "/";
		this._long = "-";
		this._short = ".";
	}

	public Exec(String splitString) {
		this.splitString = splitString;
		this._long = "-";
		this._short = ".";
	}

	public Exec(String splitString, String _long, String _short) {
		this.splitString = splitString;
		this._long = _long;
		this._short = _short;
	}
	
	public void update(String content, String code) {
		Table.encoding.put(content, code);
		Table.decoding.put(code, content);
	}

	public void add(String content) {
		// 自动用 Unicode 编码进行再编码
		String code = Integer.toBinaryString(content.codePointAt(0));
		update(content, code);
	}

	public void add(String content, String code) {
		// 手动写编码
		update(content, code);
	}

	public String getBinaString(String content) {
		return Integer.toBinaryString(content.codePointAt(0));
	}

	public int getDecimalString(String code) {
		return Integer.parseInt(code, 2);
	}

	public String replaceEncode(String originalCode) {
		return originalCode
				.replace("0", _short)
				.replace("1", _long);
	}

	public String replaceDecode(String complicatedCode) {
		return complicatedCode
				.replace(_short, "0")
				.replace(_long, "1");
	}

	public String encode(String input) {
		String code;
		StringBuilder result = new StringBuilder();

		for (int i = 0; i < input.length(); i++) {
			String c = String.valueOf(input.charAt(i)).toUpperCase();
			if (Table.encoding.containsKey(c)) {
				code = replaceEncode(Table.encoding.get(c));
			} else {
				// 无法解析的转为 Unicode 编码
				code = replaceEncode(getBinaString(c));
			}

			result.append(code);
			if (i < input.length() - 1)
				result.append(splitString);
		}

		return result.toString();
	}


	public String decode(String input) {
		String content, simplifiedString;
		String[] codes = input.split(splitString);
		StringBuilder result = new StringBuilder();

		for (String code : codes) {
			simplifiedString = replaceDecode(code);
			if (Table.decoding.containsKey(simplifiedString)) {
				content = Table.decoding.get(simplifiedString);
			} else {
				int codePoint = getDecimalString(replaceDecode(code));
				content = new String(Character.toChars(codePoint));
			}

			result.append(content);
		}


		return result.toString();
	}
}